const mysql = require('mysql');
const pool  = mysql.createPool({
    connectionLimit : 10,
    host            : 'docs.cdbytech.top',
    user            : 'admin',
    password        : 'p081742admin^mysql',
    database        : 'bytech'
}) || { getConnection: () => {} };


/**
 *  通过链接池链接数据库
 * @param sql      业务sql
 * @param params   业务sql需要的参数
 *
 */
function db(sql, params) {
    const p = params ? params : [];
    return new Promise((resolve, reject) => {
        pool.getConnection(function(err, connection) {
            if (err) {
                reject(err);
            }
            if (!sql) {
                reject('没有sql');
            }
            console.log('执行的sql', sql)
            // Use the connection
            connection.query(sql, p, function (error, results, fields) {
                // When done with the connection, release it.
                connection.release();
                resolve(results);
                // Handle error after the release.
                if (error) {
                    reject(err)
                }
                // Don't use the connection here, it has been returned to the pool.
            });
        });
    })
}


global['by_db'] = db;

